﻿Imports System.Globalization
Imports System.IO
Imports System.Drawing.Imaging

Public Class RawObjectToImageConverter
    Implements IValueConverter

    Private Shared mImageCahce As Dictionary(Of String, BitmapImage)
    Shared Sub New()
        mImageCahce = New Dictionary(Of String, BitmapImage)
    End Sub

    Public Shared Sub Decache(obj As RawObject)
        mImageCahce.Remove(obj.UniqueKey)
    End Sub

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
        ' empty images are empty...
        If value Is Nothing OrElse Not TypeOf value Is RawObject Then
            Return Nothing
        End If
        Dim obj As RawObject = CType(value, RawObject)
        Dim bmp As BitmapImage = Nothing
        If Not mImageCahce.TryGetValue(obj.UniqueKey, bmp) Then

            Dim image As System.Drawing.Image = obj.Library.GetImageForObject(obj, AppData.Config)
            ' Winforms Image we want to get the WPF Image from...
            bmp = New System.Windows.Media.Imaging.BitmapImage()
            bmp.BeginInit()
            Dim memoryStream As New MemoryStream()
            ' Save to a memory stream...
            image.Save(memoryStream, ImageFormat.Png)
            ' Rewind the stream...
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin)
            bmp.StreamSource = memoryStream
            bmp.EndInit()
            mImageCahce.Add(obj.UniqueKey, bmp)
        End If

        Return bmp
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return Nothing
    End Function
End Class
